package kafka

import (
	"gin-vue-admin/model"
	"log"
	"time"

	"github.com/Shopify/sarama"
)

const addr = "localhost:9092"
const Topic = "mindPlorer"

// Msg 定义Kafka中的消息结构
type Msg struct {
	model.ReqMessage
	Data string `json:"data"`
}

func NewSyncProducer() sarama.SyncProducer {
	cfg := newProducerCfg()
	cli, err := sarama.NewSyncProducer([]string{addr}, cfg)
	if err != nil {
		log.Fatal("NewSyncProducer failed", err.Error())
		return nil
	}
	return cli
}

func NewAsyncProducer() sarama.AsyncProducer {
	cfg := newProducerCfg()
	cli, err := sarama.NewAsyncProducer([]string{addr}, cfg)
	if err != nil {
		log.Fatal("NewAsyncProducer failed", err.Error())
		return nil
	}
	return cli
}

func newProducerCfg() *sarama.Config {
	cfg := sarama.NewConfig()
	cfg.Producer.RequiredAcks = sarama.WaitForAll
	cfg.Producer.Partitioner = sarama.NewHashPartitioner
	cfg.Producer.Retry.Max = 3
	cfg.Producer.Retry.Backoff = 100 * time.Millisecond
	cfg.Producer.Return.Successes = true
	cfg.Producer.Return.Errors = true
	cfg.Producer.Timeout = time.Second * 5
	return cfg
}
